package com.example.view;

import com.example.model.User;
import com.example.service.UserService;
import com.example.service.UserService.UserCreationResult;
import com.example.service.UserService.UserDeletionResult;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

/**
 * 用户管理视图
 */
public class UserManagementView extends JPanel {
    // 用户管理相关组件
    private JTable userTable;
    private DefaultTableModel tableModel;
    private JTextField nameField;
    private JTextField emailField;
    private UserService userService;
    
    public UserManagementView() {
        this.userService = new UserService();
        initializeUI();
        loadUserData();
    }
    
    private void initializeUI() {
        setLayout(new BorderLayout());
        
        // 创建表格
        String[] columnNames = {"ID", "姓名", "邮箱"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 禁止编辑
            }
        };
        userTable = new JTable(tableModel);
        userTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        userTable.getTableHeader().setReorderingAllowed(false);
        
        // 设置列宽
        userTable.getColumnModel().getColumn(0).setPreferredWidth(50);
        userTable.getColumnModel().getColumn(1).setPreferredWidth(150);
        userTable.getColumnModel().getColumn(2).setPreferredWidth(200);
        
        JScrollPane scrollPane = new JScrollPane(userTable);
        scrollPane.setBorder(BorderFactory.createTitledBorder("用户列表"));
        
        // 创建输入面板
        JPanel inputPanel = createUserInputPanel();
        
        // 创建按钮面板
        JPanel buttonPanel = createUserButtonPanel();
        
        // 布局
        add(scrollPane, BorderLayout.CENTER);
        add(inputPanel, BorderLayout.NORTH);
        add(buttonPanel, BorderLayout.SOUTH);
    }
    
    private JPanel createUserInputPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createTitledBorder("添加新用户"));
        
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        
        // 姓名输入
        gbc.gridx = 0; gbc.gridy = 0;
        panel.add(new JLabel("姓名:"), gbc);
        
        gbc.gridx = 1; gbc.gridy = 0;
        nameField = new JTextField(15);
        panel.add(nameField, gbc);
        
        // 邮箱输入
        gbc.gridx = 2; gbc.gridy = 0;
        panel.add(new JLabel("邮箱:"), gbc);
        
        gbc.gridx = 3; gbc.gridy = 0;
        emailField = new JTextField(20);
        panel.add(emailField, gbc);
        
        return panel;
    }
    
    private JPanel createUserButtonPanel() {
        JPanel panel = new JPanel(new FlowLayout());
        
        JButton addButton = new JButton("添加用户");
        JButton deleteButton = new JButton("删除选中用户");
        JButton refreshButton = new JButton("刷新数据");
        
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addUser();
            }
        });
        
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteSelectedUser();
            }
        });
        
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                loadUserData();
            }
        });
        
        panel.add(addButton);
        panel.add(deleteButton);
        panel.add(refreshButton);
        
        return panel;
    }
    
    private void loadUserData() {
        // 清空现有数据
        tableModel.setRowCount(0);
        
        try {
            List<User> users = userService.getAllUsers();
            for (User user : users) {
                Object[] rowData = {user.getId(), user.getName(), user.getEmail()};
                tableModel.addRow(rowData);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, 
                "加载用户数据失败: " + e.getMessage(), 
                "错误", 
                JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void addUser() {
        String name = nameField.getText().trim();
        String email = emailField.getText().trim();
        
        try {
            UserCreationResult result = userService.createUser(name, email);
            if (result.isSuccess()) {
                JOptionPane.showMessageDialog(this, 
                    result.getMessage(), 
                    "成功", 
                    JOptionPane.INFORMATION_MESSAGE);
                nameField.setText("");
                emailField.setText("");
                loadUserData(); // 刷新表格
            } else {
                JOptionPane.showMessageDialog(this, 
                    result.getMessage(), 
                    "错误", 
                    JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, 
                "添加用户时发生错误: " + e.getMessage(), 
                "错误", 
                JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void deleteSelectedUser() {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, 
                "请选择要删除的用户", 
                "提示", 
                JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        int userId = (Integer) tableModel.getValueAt(selectedRow, 0);
        String userName = (String) tableModel.getValueAt(selectedRow, 1);
        
        int confirm = JOptionPane.showConfirmDialog(this, 
            "确定要删除用户 '" + userName + "' 吗?", 
            "确认删除", 
            JOptionPane.YES_NO_OPTION);
        
        if (confirm == JOptionPane.YES_OPTION) {
            try {
                UserDeletionResult result = userService.deleteUser(userId);
                if (result.isSuccess()) {
                    JOptionPane.showMessageDialog(this, 
                        result.getMessage(), 
                        "成功", 
                        JOptionPane.INFORMATION_MESSAGE);
                    loadUserData(); // 刷新表格
                } else {
                    JOptionPane.showMessageDialog(this, 
                        result.getMessage(), 
                        "错误", 
                        JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, 
                    "删除用户时发生错误: " + e.getMessage(), 
                    "错误", 
                    JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    /**
     * 刷新数据
     */
    public void refresh() {
        loadUserData();
    }
} 